package com.psak.cudaphrasal.server.service.result;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.psak.cudaphrasal.model.SinglePhrasalResult;
import com.psak.cudaphrasal.server.service.cache.ResultsCache;
import com.psak.cudaphrasal.server.service.cache.WordHashCache;

/**
 * Usluga zarzadza wynikami przetwarzania.
 * 
 * @author piotrs10
 * 
 */
public class ResultManagementService {
	private ResultsCache resultsCache;
	private WordHashCache wordHashCache;

	/**
	 * Dekoduje aktualne wyniki z postaci hash'y slow na slowa.
	 * 
	 * @return Mapa, ktorej kluczem jest zwiazek frazeologiczny w postaci
	 *         lancucha znakow, a wartoscia liczba wystapien
	 */
	public Map<String, Long> decodeResults() {
		Map<String, Long> decodeResult = new HashMap<String, Long>();
		for (SinglePhrasalResult result : resultsCache.getResults()) {
			String phrasal = buildPhrasal(result);
			long numberOfOccurences = result.getNumberOfOccurences();
			decodeResult.put(phrasal, numberOfOccurences);
		}
		return decodeResult;
	}

	/**
	 * Dodaje i merge'uje nowe wyniki z aktualnymi.
	 * 
	 * @param newResult
	 */
	public void mergeAndAddResults(List<SinglePhrasalResult> newResult) {

		List<SinglePhrasalResult> currentResults = resultsCache.getResults();
		for (SinglePhrasalResult singlePhrasalResult : newResult) {
			boolean resultFound = false;
			for (SinglePhrasalResult currentResult : currentResults) {
				if (currentResult.getPhrasalHash().equals(
						singlePhrasalResult.getPhrasalHash())) {
					resultFound = true;
					currentResult.setNumberOfOccurences(currentResult
							.getNumberOfOccurences()
							+ singlePhrasalResult.getNumberOfOccurences());
					break;
				}
			}
			if (!resultFound) {
				currentResults.add(singlePhrasalResult);
			}
			resultFound = false;
		}
	}

	private String buildPhrasal(SinglePhrasalResult result) {
		StringBuilder phrasalBuilder = new StringBuilder();
		for (long wordHash : result.getPhrasalHash()) {
			String word = wordHashCache.get(wordHash);
			phrasalBuilder.append(word);
			phrasalBuilder.append(" ");
		}

		return phrasalBuilder.toString().trim();
	}

	/**
	 * Sprawdza czy wszystkie wyniki juz dotarly.
	 * 
	 * @return Jezeli dotarly - true
	 */
	public boolean isResultCollected() {
		return resultsCache.isFull();
	}

	public void setResultsCache(ResultsCache resultsCache) {
		this.resultsCache = resultsCache;
	}

	public void setWordHashCache(WordHashCache wordHashCache) {
		this.wordHashCache = wordHashCache;
	}

}
